3
3
.
.
1
1
.
.
4
4
@
@
B
B
i
i
n
n
d
d
i
i
n
n
g
g
I
I
n
n
f
f
o
o
[
[
R
R
]
]
@Binding is used to declare that Variable is a Reference to another Variable.
That means that both Variables will point to the same place/data/instance.
They become synched - they become the same Variable.
Content
Without @Binding
With @Binding
Two way @Binding
W
W
i
i
t
t
h
h
o
o
u
u
t
t
@
@
B
B
i
i
n
n
d
d
i
i
n
n
g
g
In this example we have a Button that toggles @State Variable show which controls Text Color.
ContentView.swift
struct ContentView : View {
@State var show = true
var body:some View {
VStack(spacing: 20) {
Text("TEXT").foregroundColor(show ? .blue : .red)
Button("TOGGLE") { self.show.toggle() }
}
}
}
W
W
i
i
t
t
h
h
@
@
B
B
i
i
n
n
d
d
i
i
n
n
g
g
Lets say that we want to move the Button into separate View but we still want to be able to control @State Variable show
We can do that by creating a reference to show in this new View as highlighted in yellow.
Now changing isPresented in the new View actually changes show in the original View.
This is because isPresented s just a reference to show - it points to show Variable.
ContentView.swift
import SwiftUI
struct ContentView : View {
@State var show = true
var body:some View {
VStack(spacing: 20) {
Text("TEXT").foregroundColor(show ? .blue : .red)
ToggleButton(isPresented: $show)
}
}
}
struct ToggleButton: View {
@Binding var isPresented: Bool
var body: some View {
Button("TOGGLE") { self.isPresented.toggle() }
}
}
T
T
w
w
o
o
w
w
a
a
y
y
@
@
B
B
i
i
n
n
d
d
i
i
n
n
g
g
In this example we add a Button to the Main View which changes show Variable.
And we add Text to the Sub View which changes color based on isPresented.
When we press this Button it changes show Variable.
But since show and isPresented can be considered the same Variables this also changes isPresented Variable.
Which in turn changes color of the Text in the Sub View which depends on isPresented Variable.
ContentView.swift
struct ContentView : View {
@State var show = true
var body:some View {
VStack(spacing: 20) {
Text("MAIN VIEW").foregroundColor(show ? .blue : .red)
Button("CHANGE") { self.show.toggle() }
ToggleButton(isPresented: self.$show)
}.padding().border(Color.blue, width: 3)
}
}
struct ToggleButton: View {
@Binding var isPresented: Bool
var body: some View {
VStack(spacing: 20) {
Text("SUB VIEW").foregroundColor(isPresented ? .blue : .red)
Button("TOGGLE") { self.isPresented.toggle() }
}.padding().border(Color.red, width: 3)
}
}